package com.svs.web.controller.system;

import com.microsoft.sqlserver.jdbc.StringUtils;
import com.svs.common.annotation.Log;
import com.svs.common.base.AjaxResult;
import com.svs.common.enums.BusinessType;
import com.svs.common.support.Convert;
import com.svs.common.utils.ExcelUtil;
import com.svs.framework.shiro.util.ShiroUtils;
import com.svs.framework.util.ServletUtils;
import com.svs.framework.web.BackendController;
import com.svs.framework.web.page.TableDataInfo;
import com.svs.system.cache.SysDicCache;
import com.svs.system.domain.SysDictData;
import com.svs.system.service.SysDictDataService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据字典信息
 *
 * @author dujianqiao
 */
@Controller
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BackendController {
    private String prefix = "system/dict/data";

    @Autowired
    private SysDictDataService dictDataService;

    @RequiresPermissions("system:dict:view")
    @GetMapping()
    public String dictData() {
        return prefix + "/data";
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/list")
    @ResponseBody
    public TableDataInfo list(SysDictData dictData) {
        if (StringUtils.isEmpty(dictData.getDictType())) {
            String dictType = ServletUtils.getSession().getAttribute("dictType") + "";
            dictData.setDictType(dictType);
        }
        startPage();
        List<SysDictData> list = dictDataService.selectAllList(dictData);
        return getDataTable(list);
    }

    @GetMapping("/treeList")
    @ResponseBody
    public List<SysDictData> treeList(SysDictData dictData) {
        if (StringUtils.isEmpty(dictData.getDictType())) {
            String dictType = ServletUtils.getSession().getAttribute("dictType") + "";
            dictData.setDictType(dictType);
        }
        List<SysDictData> list = dictDataService.selectAllList(dictData);
        //处理数据
        List<SysDictData> rootList = new ArrayList<>();
        Map<Long, List<SysDictData>> dataMap = new HashMap<>();
        list.forEach(tem -> {
            if (tem.getParentCode() == 0) {//根节点
                rootList.add(tem);
            } else {
                List<SysDictData> temList = dataMap.get(tem.getParentCode());
                if (null == temList) {
                    temList = new ArrayList<>();
                    dataMap.put(tem.getParentCode(), temList);
                }
                temList.add(tem);
            }
        });
        //将子节点放到对应的list中去
        list.forEach(tem -> {
            tem.setSubList(dataMap.get(tem.getDictCode()));
        });
        return rootList;
    }

    @Log(title = "字典数据", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:dict:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysDictData dictData) {
        List<SysDictData> list = dictDataService.selectAllList(dictData);
        ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
        return util.exportExcel(list, "dictData");
    }

    /**
     * 新增字典类型
     */
    @GetMapping("/add/{dictType}")
    public String add(@PathVariable("dictType") String dictType, ModelMap mmap) {
        String[] datas = Convert.toStrArray(dictType);
        mmap.put("dictType", dictType);
        mmap.put("parentCode", "0");
        if (datas.length > 1) {
            mmap.put("dictType", datas[0]);
            mmap.put("parentCode", datas[1]);
        }

        return prefix + "/add";
    }

    /**
     * 新增保存字典类型
     */
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:dict:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysDictData dict) {
        dict.setCreateBy(ShiroUtils.getLoginName());
        int result = dictDataService.save(dict);
        SysDicCache.getCache().init();
        return toAjax(result);
    }

    /**
     * 修改字典类型
     */
    @GetMapping("/edit/{dictCode}")
    public String edit(@PathVariable("dictCode") Long dictCode, ModelMap mmap) {
        mmap.put("dict", dictDataService.selectByPrimaryKey(dictCode));
        return prefix + "/edit";
    }


    /**
     * 修改字典类型
     */
    @GetMapping("/queryChild/{dictCode}")
    @ResponseBody
    public List<SysDictData> queryChild(@PathVariable("dictCode") Long dictCode) {
        SysDictData data = dictDataService.selectByPrimaryKey(dictCode);
        String type = null != data ? data.getDictType() : "";
        List<SysDictData> childList = SysDicCache.getCache().getChildrenList(type, dictCode);
        return childList;
    }

    /**
     * 修改保存字典类型
     */
    @Log(title = "字典数据", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:dict:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysDictData dict) {
        dict.setUpdateBy(ShiroUtils.getLoginName());
        int result = dictDataService.update(dict);
        SysDicCache.getCache().init();
        return toAjax(result);
    }

    @Log(title = "字典数据", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:dict:remove")
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(@RequestParam("ids") String[] id) {
        int result = dictDataService.deleteByPrimaryKeys(id);
        SysDicCache.getCache().init();
        return toAjax(result);
    }
}
